package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.dubbo.config.annotation.Service;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        if(setmeal.getImg() != null){
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        }
        Integer setmealId = setmeal.getId();
        if(checkgroupIds != null && checkgroupIds.length > 0){
            this.setmealAndCheckgroup(setmealId,checkgroupIds);
        }
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
        List<Setmeal> setmealList = setmealDao.getAllSetmeal();

        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {

        for (Setmeal setmeal : setmealList) {
            HashMap<String, Object> map = new HashMap<>();

            if(setmeal.getHelpCode() != null || setmeal.getSex() != null || setmeal.getAge() != null || setmeal.getRemark() != null || setmeal.getImg() != null){
                map.put("setmealList",setmealList);
                this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
            }
            if(setmeal.getHelpCode() == null || setmeal.getSex() == null || setmeal.getAge() == null || setmeal.getRemark() == null || setmeal.getImg() == null){
                setmeal.setHelpCode("无");
                setmeal.setSex("无");
                setmeal.setAge("无");
                setmeal.setRemark("无");
                setmeal.setImg("无");
                map.put("setmealList",setmealList);
                this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",map);
            }

        }

    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            HashMap<String, Object> map = new HashMap<>();
            Setmeal setmeal2 = this.findById(setmeal.getId());
            if(setmeal2.getHelpCode() != null || setmeal2.getSex() != null || setmeal2.getAge() != null || setmeal2.getRemark() != null || setmeal2.getImg() != null){
                map.put("setmeal",setmeal2);
                this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+ setmeal.getId() + ".html",map);
            }
            if(setmeal2.getHelpCode() == null || setmeal2.getSex() == null || setmeal2.getAge() == null || setmeal2.getRemark() == null || setmeal2.getImg() == null){
                    setmeal2.setHelpCode("无");
                    setmeal2.setSex("无");
                    setmeal2.setAge("无");
                    setmeal2.setRemark("无");
                    setmeal2.setImg("无");
                    map.put("setmeal",setmeal2);
                    this.generateHtml("mobile_setmeal_detail.ftl","setmeal_detail_"+
                            setmeal.getId() + ".html",map);
            }
            System.out.println(setmeal2.getRemark());

        }
    }

    public void generateHtml(String templateName,String htmlPageName,Map<String,Object> map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try{
            Template template = configuration.getTemplate(templateName);
            File file = new File(outPutPath + "\\" + htmlPageName);
            out = new FileWriter(file);
            template.process(map,out);
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                if(out != null){
                    out.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
//        Page<Setmeal> pages = setmealDao.findPage(queryString);
        Page<Setmeal> pages = setmealDao.findByCondition(queryString);
        return new PageResult(pages.getTotal(),pages.getResult());
    }

    @Override
    public List<Setmeal> getAllSetmeal() {
        return setmealDao.getAllSetmeal();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    //查询套餐关联的所有检查组id
    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        return setmealDao.findCheckGroupIdsBySetmealId(id);
    }

    public void setmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds){
        Map<String,Integer> map = null;
        for (Integer checkgroupId : checkgroupIds) {
            map = new HashMap<String, Integer>();
            map.put("setmealId",setmealId);
            map.put("checkgroupId",checkgroupId);
            setmealDao.setmealAndCheckgroup(map);
        }
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //修改检查组基本信息
        setmealDao.edit(setmeal);
        //清理当前检查组关联的检查项，操作中间关系表
        setmealDao.deleteAssocication(setmeal.getId());
        //重新建立关联关系
        setSetmealAndCheckgroup(setmeal.getId(),checkgroupIds);
    }

    /**
     * 关联检查组方法
     */
    public void setSetmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds){
        if(checkgroupIds != null && checkgroupIds.length > 0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("setmealId",setmealId);
                map.put("checkgroupId",checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }

    @Override
    public void delete(Integer id){
        //删除关联关系(先删除)
        setmealDao.deleteAssocication(id);
        //删除本表数据
        setmealDao.delete(id);
    }

    // 查询所有套餐
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }
}
